package com.web.pay_service.schedule;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.web.pay_service.pojo.Order;
import com.web.pay_service.service.OrderService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.scheduling.annotation.Scheduled;
import org.springframework.stereotype.Component;

import java.time.Duration;
import java.time.LocalDateTime;
import java.util.List;

@Component
public class FinishtradeSchedule {

    @Autowired
    OrderService orderService;

    // 每天凌晨进行检查 如果有记录超过了7天 自动确认
    @Scheduled(cron = "0 0 0 * * ? ")
    public void finishTrade()
    {
        // 1. 先将所有状态为未完成的记录取出来
        QueryWrapper<Order> queryWrapper=new QueryWrapper<>();
        queryWrapper.eq("state", 0);

        List<Order> orderList = orderService.list(queryWrapper);

        // 2. 遍历整个记录 将完成的且创建时间已经大于7天的记录自动确认
        LocalDateTime now = LocalDateTime.now();

        for (Order order : orderList) {
            // 计算日期
            LocalDateTime createTime = order.getCreateTime();
            Duration duration = Duration.between(createTime, now);

            long days = duration.toDays();

            if (days>=7)
            {
                order.setFinishTime(now);
                order.setState(1);

                orderService.updateById(order);
            }

        }

    }

}
